package com.slz3.business.module.messageManagement.mesTemplate.service;

import com.slz3.business.frame.enums.ValidFlag;
import com.slz3.business.frame.module.Repositorys;
import com.slz3.business.frame.module.Services;
import com.slz3.business.frame.steward.PageableSteward;
import com.slz3.business.module.messageManagement.mesTemplate.domain.MesTemplate;
import com.slz3.business.module.messageManagement.mesTemplate.domain.MesTemplateFactory;
import com.slz3.business.module.messageManagement.mesTemplate.steward.MesTemplateSpecification;
import com.slz3.business.module.messageManagement.mesType.domain.MesType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MesTemplateServiceImpl implements MesTemplateService {
    @Override
    public MesTemplate save(MesTemplate mesTemplate) {
        return Repositorys.mesTemplate.save(MesTemplateFactory.initBaseFields(mesTemplate));
    }

    @Override
    public Page<MesTemplate> page(MultiValueMap<String, String> params) {
        Page<MesTemplate> mesTemplatePage = Repositorys.mesTemplate.findAll(
                MesTemplateSpecification.findJoin(params), PageableSteward.extract(params)
        );
        //
        Map<UUID, MesType> mesTypeMap = Repositorys.mesType.findAll().stream().collect(Collectors.toMap(MesType::getUuid, Function.identity()));
        //
        mesTemplatePage.stream().forEach(item -> item.setMesType(mesTypeMap.get(item.getFkMesType())));
        return mesTemplatePage;
    }


    @Override
    public MesTemplate modify(MesTemplate mesTemplateNew) {
        return Repositorys.mesTemplate.saveAndFlush(MesTemplateFactory.initBaseFields(mesTemplateNew));
    }

    @Override
    public Optional<MesTemplate> single(UUID uuid) {
        return Repositorys.mesTemplate.findById(uuid);
    }

    @Override
    public List<MesTemplate> findAllByUuids(Iterable<UUID> uuids) {
        return Repositorys.mesTemplate.findAllById(uuids);
    }

    @Override
    public List<MesTemplate> delete(List<MesTemplate> mesTemplateList) {
        mesTemplateList.stream().forEach(item -> {
            item.setValidFlag(ValidFlag.DEL);
            MesTemplateFactory.initBaseFields(item);
        });
        return Services.mesTemplateTransactional.batchModify(mesTemplateList);
    }

}
